const QQMapWX = require('../libs/qqmap-wx-jssdk.js');

const qqmapsdk = new QQMapWX({
  key: "UPVBZ-H466S-FCNOQ-6Y4Q3-LNLWH-C3FYT"
});

const reverseGeocoder = (latitude, longitude) => {
  return new Promise((resolve, reject) => {
    let location = '';
    if (latitude || longitude) {
      location = {
        latitude: latitude,
        longitude: longitude,
      };
    }

    qqmapsdk.reverseGeocoder({
      location: location,
      success: function(res) {
        console.log(res);
        resolve(res.result);
      },
      fail: function(error) {
        reject(error);
      },
      complete: function(res) {
        console.log(res);
      }
    });
  });
};

const secondformatTime = (s) => {
  s = parseInt(s.toString());
  let minute = parseInt((s / 60).toString());
  let second = parseInt((s % 60).toString());

  if (minute.toString().length < 2) {
    minute = parseInt(`0${minute}`);
  }
  if (second.toString().length < 2) {
    second = parseInt(`0${second}`);
  }

  return `${minute}:${second}`;
};

function getRndInteger(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

const openConfirm = (thing) => {
  return new Promise((resolve, reject) => {
    const key = 'scope.' + thing;
    let title = '';

    switch (thing) {
      case 'record':
        title = '录音';
        break;
      case 'userLocation':
        title = '位置';
        break;
    }

    wx.getSetting({
      success(res) {
        console.log(res.authSetting[key]);
        if (!res.authSetting[key]) {
          wx.showModal({
            content: '检测到您尚未开启' + title + '权限，请前往开启',
            confirmText: "开启",
            cancelText: "取消",
            success: function(res) {
              if (res.confirm) {
                wx.openSetting({
                  complete: (res) => {
                    if (res.authSetting[key]) {
                      resolve(res);
                    }
                  }
                });
              } else {
                reject();
              }
            }
          });
        } else {
          resolve(res);
        }
      }
    });
  });
};

const isBlank = (obj) => {
  const type = Object.prototype.toString.call(obj);
  if (type === '[object Undefined]') return true;
  if (type === '[object String]' || type === '[object Array]') return obj.length === 0;
  if (type === '[object Object]') return JSON.stringify(obj) === '{}';
  return true;
};

const isArrayFn = (value) => {
  if (typeof Array.isArray === "function") {
    return Array.isArray(value);
  } else {
    return Object.prototype.toString.call(value) === "[object Array]";
  }
};

const rpx2px = (rpx) => {
  const rate = wx.getSystemInfoSync().windowWidth / 750;
  return rate * rpx;
};

function getRpx() {
  const winWidth = wx.getSystemInfoSync().windowWidth;
  return winWidth / 750;
}

const stringFormatTime = (dateStr, type = 1) => {
  const date = new Date(dateStr);
  return dateFormatTime(date, type);
};

const dateFormatTime = (date, type = 1) => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  switch (type) {
    case 1:
      return [year, month, day].map(formatNumber).join('-');
    case 2:
      return [hour, minute, second].map(formatNumber).join(':');
    default:
      return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':');
  }
};

const formatNumber = (n) => {
  n = n.toString();
  return n[1] ? n : '0' + n;
};

const md5 = (string) => {
  console.log(string); // 实际开发中应替换为真实 md5 方法
};

const formattimestamp = (number, format) => {
  const formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  const returnArr = [];

  const date = new Date(number * 1000);
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));
  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));

  for (let i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i].toString());
  }
  return format;
};

module.exports = {
  reverseGeocoder,
  secondformatTime,
  getRndInteger,
  openConfirm,
  isBlank,
  isArrayFn,
  rpx2px,
  getRpx,
  stringFormatTime,
  dateFormatTime,
  md5,
  formattimestamp
};